package api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import common.ApplicationVariable;
import lombok.SneakyThrows;
import model.Dish;
import model.ResultData;
import util.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * 查询所有的菜品信息
 */
@WebServlet("/dishlist")
public class DishListServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType(ApplicationVariable.RESPONSE_CONTENT_TYPE);
        List<Dish> list = new ArrayList<>();
        // 是否下架（非必传参数）
        String isdownStr = req.getParameter("isdown");
        Integer isdown = -1; // 是否下架
        if (!StrUtil.isBlank(isdownStr) && isdownStr.equals("0")) {
            // 有效参数，表示查询未下架的菜品
            isdown = 0;
        }
        // 查询数据库得到菜品列表
        Connection connection = DBUtil.getConnection();
        String sql = "select * from dish";
        if (isdown == 0) sql += " where isdown=?";
        PreparedStatement statement = connection.prepareStatement(sql);
        if (isdown == 0) statement.setInt(1, 0);
        ResultSet resultSet = statement.executeQuery();
        while (resultSet.next()) {
            Dish dish = new Dish();
            dish.setDid(resultSet.getInt("did"));
            dish.setName(resultSet.getString("name"));
            dish.setPrice(resultSet.getBigDecimal("price"));
            dish.setIsdown(resultSet.getInt("isdown"));
            dish.setCreatetime(resultSet.getString("createtime"));
            dish.setSelect(false);
            list.add(dish);
        }
        // 关闭资源
        DBUtil.close(resultSet, statement, connection);
        resp.getWriter().println(JSONUtil.toJsonStr(
                new ResultData(200, list, "")
        ));
    }
}
